<template>
  <div class="save-box">
    <Button style="margin-left: 5px" type="text" @click="beforeClear">清空</Button>
    <Button style="margin-left: 5px" type="text" @click="preview">预览</Button>
    <Dropdown style="margin-left: 5px" @on-click="saveWith">
      <Button type="primary" style="padding: 0 1.5em">
        保存
        <Icon type="ios-arrow-down"></Icon>
      </Button>
      <template #list>
        <DropdownMenu>
          <!-- <DropdownItem name="clipboard">复制到剪切板</DropdownItem> -->
          <DropdownItem name="saveImg">PNG无损图片</DropdownItem>
          <DropdownItem name="saveJPG">Jpeg图片</DropdownItem>
          <!-- <DropdownItem name="saveSvg">保存为SVG</DropdownItem> -->
          <DropdownItem name="saveJson">保存代码</DropdownItem>
        </DropdownMenu>
      </template>
    </Dropdown>
  </div>
  <Modal
    v-model="modal.type"
    title="JPG图片质量选择"
    @on-ok="() => canvasEditor.saveImg('jpeg', Number(modal.value) / 100)"
  >
    <p>值越大，质量越高，取值范围 【0-100】</p>
    <Slider v-model="modal.value" :max="100" :min="0" :step="1" show-input></Slider>
  </Modal>
</template>

<script setup name="save-bar">
import { Modal, ImagePreview } from 'view-ui-plus';
import useSelect from '@/hooks/select';
import { debounce } from 'lodash-es';
// import { downloadFile } from '@/utils/utils';

const { canvasEditor } = useSelect();
const cbMap = {
  clipboard() {
    canvasEditor.clipboard();
  },

  saveJson() {
    canvasEditor.saveJson();
  },

  saveSvg() {
    canvasEditor.saveSvg();
  },

  saveImg() {
    canvasEditor.saveImg();
    // 弹出选择 - 质量+类型
  },
};

const modal = reactive({
  type: false,
  value: 100,
});
const saveWith = debounce(function (type) {
  if (type == 'saveJPG') {
    modal.type = true;
    return;
  }
  cbMap[type] && typeof cbMap[type] === 'function' && cbMap[type]();
}, 300);

/**
 * @desc clear canvas 清空画布
 */
const clear = () => {
  canvasEditor.clear();
};

const beforeClear = () => {
  Modal.confirm({
    title: '提示',
    content: '<p>确定要清空吗？</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: () => clear(),
  });
};

// 预览事件
const preview = () => {
  canvasEditor.preview().then((dataUrl) => {
    ImagePreview.show({
      previewList: [dataUrl],
    });
  });
};
</script>

<style scoped lang="less">
.save-box {
  display: inline-block;
  padding-right: 10px;
}
</style>
